﻿using System;
using System.Collections.Generic;
using System.Text;

namespace TC.Vacation.Spider.Web
{
    internal static class HtmlEncoding
    {
        private static Dictionary<string, EncodingInfo> _Encodings;

        /// <summary>
        /// 获取系统编码字典
        /// </summary>
        private static Dictionary<string, EncodingInfo> Encodings
        {
            get
            {
                if (_Encodings == null)
                {
                    _Encodings = new Dictionary<string, EncodingInfo>(StringComparer.CurrentCultureIgnoreCase);
                    foreach (var encoding in Encoding.GetEncodings())
                    {
                        _Encodings[encoding.Name] = encoding;
                    }
                }
                return _Encodings;
            }
        }

        /// <summary>
        /// 尝试根据名称获取一个编码
        /// </summary>
        /// <param name="encodingName"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static bool TryGetEncoding(string encodingName, out Encoding encoding)
        {
            EncodingInfo info;
            if (Encodings.TryGetValue(encodingName, out info))
            {
                encoding = info.GetEncoding();
                return true;
            }
            else
            {
                encoding = null;
                return false;
            }
        }

        /// <summary>
        /// 根据名称获取一个编码
        /// </summary>
        /// <param name="encodingName"></param>
        /// <returns></returns>
        public static Encoding GetEncoding(string encodingName)
        {
            Encoding encoding;
            if (TryGetEncoding(encodingName, out encoding))
            {
                return encoding;
            }
            else
            {
                return null;
            }
        }
    }
}
